<template>
  <div style="font-size: 14px">
    <el-drawer v-model="dialogVisible" :title="form.ciId ? '编辑资产' : '新增资产'" direction="rtl" size="1000">
      <div>
        <table>
          <tr>
            <!-- <td><el-button type="primary" @click="onSubmitFormPre(ruleFormRef)"> 保存 </el-button></td> -->
            <!-- <td><el-button type="primary" @click="backList"> 返回列表 </el-button></td> -->
            <td>类似表单：</td>
            <td :style="{ width: '200px' }">
              <el-select v-model="similarFormCustom" @change="similarFormCustomChange">
                <el-option
                  v-for="item in similarFormCustomOptions"
                  :key="item.templateId"
                  :label="item.templateName"
                  :value="item.templateId"
                />
              </el-select>
            </td>

            <td @click="dialogCicategoryVisible = true">配置项分类</td>
            <td>
              <el-input v-model="form.categoryName" id="customerTypeNameInput" @click="dialogCicategoryVisible = true" />
            </td>
            <td>
              <p v-if="form.categoryNo == null || form.categoryNo == ''" style="font-size: 20px; color: red">请选择配置项分类</p>
            </td>
          </tr>
        </table>
        <el-dialog title="选择配置项分类" v-model="dialogCicategoryVisible">
          <div :style="{ height: '500px' }">
            <el-tree
              :data="categorySelectList"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="handleNodeClickcategory"
              class="custom-tree"
            />
          </div>
        </el-dialog>
      </div>
      <div v-loading="loading">
        <el-form
          ref="editForm"
          v-if="dialogVisible"
          :model="form"
          :rules="rules"
          label-width="120"
          :disabled="form.categoryNo == ''"
        >
          <div v-if="showCustomerForm == false">
            <el-row>
              <el-col :span="12">
                <el-form-item label="资产名称" prop="ciname">
                  <el-input v-model="form.ciname" placeholder="请输入资产名称" />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
              <el-form-item label="配置项分类" prop="categoryNo">
                <div style="display: flex; width: 100%">
                  <el-input
                    style="flex: 1; overflow: hidden"
                    v-model="form.categoryName"
                    placeholder="请选择配置项分类"
                    :readonly="true"
                    clearable
                  ></el-input>
                  <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectConfigItem"></el-button>
                </div>
              </el-form-item>
            </el-col> -->
              <el-col :span="12">
                <el-form-item label="固定资产编号" prop="cino">
                  <el-input v-model="form.cino" placeholder="请输入固定资产编号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属客户" prop="companyNo">
                  <el-select v-model="form.companyNo" :disabled="form.ciId ? true : false" @change="companyChange">
                    <el-option
                      v-for="(item, index) in orgList"
                      :key="index"
                      :label="item.orgName"
                      :value="item.orgNo"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="statusId">
                  <el-select v-model="form.statusId" placeholder="请选择状态">
                    <el-option v-for="item in statusList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="位置" prop="locId">
                  <el-tree-select
                    v-model="form.locId"
                    :data="positionList"
                    check-strictly
                    :render-after-expand="false"
                    @change="locChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采购日期" prop="buyDate">
                  <el-date-picker
                    v-model="form.buyDate"
                    type="date"
                    placeholder="请选择日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="到货日期" prop="arrivalDate">
                  <el-date-picker
                    v-model="form.arrivalDate"
                    type="date"
                    placeholder="请选择日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预警日期" prop="warningDate">
                  <el-date-picker
                    v-model="form.warningDate"
                    type="date"
                    placeholder="请选择日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生命周期(月)" prop="lifeCycle">
                  <el-input type="number" v-model="form.lifeCycle" :min="0" :max="120" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="保修期(月)" prop="warranty">
                  <el-input type="number" v-model="form.warranty" :min="0" :max="120" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资产原值" prop="assetsOriginalValue">
                  <el-input type="number" v-model="form.assetsOriginalValue" :min="0" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门" prop="department">
                  <div style="display: flex; width: 100%">
                    <el-input
                      style="flex: 1; overflow: hidden"
                      v-model="form.department"
                      placeholder="请选择部门"
                      :readonly="true"
                      clearable
                    ></el-input>
                    <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectDepartment"></el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="owner">
                  <div style="display: flex; width: 100%">
                    <el-input
                      style="flex: 1; overflow: hidden"
                      v-model="form.owner"
                      placeholder="请选择负责人"
                      :readonly="true"
                      clearable
                    ></el-input>
                    <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectUser('owner')"></el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="使用人" prop="userName">
                  <div style="display: flex; width: 100%">
                    <el-input
                      style="flex: 1; overflow: hidden"
                      v-model="form.userName"
                      placeholder="请选择使用人"
                      :readonly="true"
                      clearable
                    ></el-input>
                    <el-button
                      style="margin-left: 10px"
                      type="primary"
                      :icon="Search"
                      @click="selectUser('userName')"
                    ></el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="折旧年限(年)" prop="depreciationIsZeroYears">
                  <el-input v-model="form.depreciationIsZeroYears" :min="0" :max="20" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div v-if="showCustomerForm == true">
            <form-create v-model="formData" :option="option" :rule="formCreateRules" />
          </div>
          <el-dialog title="选择客户" v-model="dialogCiCompanyNoTableVisible">
            <div :style="{ height: '500px' }">
              <Custemerselect @send-data="sendCiCompanyNoData" />
            </div>
          </el-dialog>
          <el-dialog title="选择位置" v-model="dialogLocationTableVisible">
            <div :style="{ height: '500px' }">
              <el-tree
                :data="LocationSelectList"
                :props="defaultProps"
                :default-expand-all="true"
                @node-click="handleNodeClickLocation"
                class="custom-tree"
              />
              <el-button class="dialogOkBtn" type="primary" @click="submitLocation" style="min-width: 80px"> 确 定 </el-button>
            </div>
          </el-dialog>
          <el-dialog title="选择部门" v-model="dialogDepartmentVisible">
            <div :style="{ height: '500px' }">
              <el-tree
                :data="departmentSelectList"
                :props="defaultProps"
                :default-expand-all="true"
                @node-click="handleNodeClickDepartment"
                class="custom-tree"
              />
              <el-button class="dialogOkBtn" type="primary" @click="submitDepartment" style="min-width: 80px"> 确 定 </el-button>
            </div>
          </el-dialog>
          <el-dialog title="选择负责人" v-model="dialogOwnerVisible">
            <div :style="{ height: '500px' }">
              <Userselect @send-data="sendOwner" :father="fatherValue" />
            </div>
          </el-dialog>
          <el-dialog title="选择使用人" v-model="dialogUserNameVisible">
            <div :style="{ height: '500px' }">
              <Userselect @send-data="sendUserNamer" :father="fatherValue" />
            </div>
          </el-dialog>

          <el-row>
            <el-col :span="24">
              <el-tabs v-model="tabName" class="demo-tabs">
                <el-tab-pane label="附件" name="one">
                  <EnclosureList v-if="form.ciId" :ci-id="details.ciId" event-type="itsm.configureItem"></EnclosureList>
                  <div v-else>
                    <el-upload ref="uploadRef" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadChange">
                      <template #trigger>
                        <el-button type="primary" plain>添加附件</el-button>
                      </template>
                    </el-upload>
                    <el-table
                      :data="enclosureList"
                      border
                      style="margin-top: 10px"
                      :height="enclosureList.length > 0 ? '' : 100"
                      max-height="400px"
                    >
                      <el-table-column label="名称" prop="attachmentName"></el-table-column>
                      <el-table-column label="服务器路径" prop="url"></el-table-column>
                      <el-table-column label="操作" align="center" width="180">
                        <template #default="scope">
                          <el-button @click="delFile(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="关联服务" name="two">
                  <div style="margin-bottom: 10px">
                    <el-button type="primary" plain @click="showSelectServesMask">添加服务</el-button>
                  </div>
                  <el-table
                    border
                    :data="serviceDirectoryList"
                    :height="serviceDirectoryList.length > 0 ? '' : 100"
                    max-height="400px"
                  >
                    <el-table-column type="index" label="序号" width="150" align="center"></el-table-column>
                    <el-table-column label="服务名称" prop="cname"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                      <template #default="scope">
                        <el-button @click="delServe(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <div v-if="showCustomerForm == true">
                  <el-tab-pane :label="item.tabName" :name="item.tabName" v-for="(item, index) in tabList" :key="index">
                    <form-create v-model="item.formData" :option="item.option" :rule="item.formCreateRules" />
                  </el-tab-pane>
                </div>
              </el-tabs>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-drawer>
    <!-- 选择配置项 -->
    <SelectConfigItem ref="selectConfigItemMask" @change="selectConfigItemChange"></SelectConfigItem>
    <!-- 选择部门 -->
    <SelectDepartment ref="selectDepartmentMask" @change="departmentChange"></SelectDepartment>
    <!-- 选择用户弹窗 -->
    <SelectUserMask ref="selectUserMask" @change="userChange"></SelectUserMask>
    <!-- 选择服务 -->
    <SelectServesMask v-if="dialogVisible" ref="selectServesMask" @change="serveChange"></SelectServesMask>
  </div>
</template>

<script setup lang="ts" name="EditAssetMask">
import { ref, reactive, computed, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";

import SelectUserMask from "@/components/SelectUserMask/index.vue";
import SelectServesMask from "@/components/SelectServesMask/index.vue";
import EnclosureList from "@/components/EnclosureList/index.vue";
import SelectConfigItem from "@/components/SelectConfigItem/SelectConfigItem.vue";
import SelectDepartment from "@/components/SelectDepartment/SelectDepartment.vue";

import { uploadAttr, findAllOrganization } from "@/api/modules/common";
import { findById, cItemSave, cItemUpdate, findAllTemplate } from "@/api/modules/assetManagement";

import { allAssetOptions } from "@/stores/modules/asset";

import { useUserStore } from "@/stores/modules/user";
import { getCimClass } from "@/api/modules/dictionary";
import { findFormCustomByCiCategoryNo } from "@/api/modules/systemTools";
import { Base64 } from "js-base64";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import Custemerselect from "@/views/tools/custemerSelect/index.vue";
import { getUserDepartment } from "@/api/modules/jggl";
import Userselect from "@/views/tools/userSelectbyOrgNo/index.vue";
const userStore = useUserStore();

const assetOptions = allAssetOptions();

const dialogVisible = ref(false);

//资产内容模板
const similarFormCustom = ref();
const similarFormCustomOptions = ref<any>([]);
const similarFormCustomChange = (data: any) => {
  let tmpDefaultFormCreateRules = [];
  similarFormCustomOptions.value.forEach(item => {
    console.log(item);
    console.log(data);

    if (data == item.templateId) {
      console.log("xuznzzzzzz");
      console.log();
      console.log(data);
      let newPitemms = JSON.parse(item.templateJson);
      console.log("newPitemms");
      console.log(newPitemms);
      details.value = {
        ...details.value,
        ...newPitemms
      };
      serviceDirectoryList.value = [];
      // 设置关联服务列表
      if (details.value.serviceNos != null && details.value.serviceNos != "") {
        if ("length" in details.value.serviceNos) {
          console.log("myVar is an array");
          for (let i = 0; i < details.value.serviceNos.length; i++) {
            Object.keys(details.value.serviceNos[i]).forEach(key => {
              serviceDirectoryList.value.push({ id: key, cname: details.value.serviceNos[i][key] });
            });
          }
        } else {
          Object.keys(details.value.serviceNos).forEach(key => {
            serviceDirectoryList.value.push({
              id: key,
              cname: details.value.serviceNos[key]
            });
          });
          console.log("myVar is an object");
        }
      } else {
        serviceDirectoryList.value = [];
      }
      let valArr = newPitemms.attachmentStr.split("-s-");
      for (let i = 0; i < valArr.length; i++) {
        if (valArr[i] == "") {
          continue;
        }
        let attObj = valArr[i].split("==");
        // let attachment =
        enclosureList.value.push({
          attachmentName: attObj[0],
          url: attObj[1],
          size: attObj[2]
        });
      }
      //自定义表单
      findFormCustomByCiCategoryNo(newPitemms.categoryNo).then(res => {
        if (res != null) {
          showCustomerForm.value = true;
          console.log("res");
          console.log(res);
          let formCustomRes = JSON.parse(JSON.stringify(res));
          let yyde = Base64.decode(formCustomRes.formCustomContents); //解密
          console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          for (let i = 0; i < a.length; i++) {
            if (a[i].label != undefined && a[i].label != "") {
              showCustomerForm.value = false;
              break;
            }
            if (a[i].title == "所属客户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCiCompanyNoTableVisible.value = true;
                }
              };
            }
            // if(a[i].title=="请求分类"){
            // 	a[i]["on"]={
            // 			focus(inject){
            // 				dialogRequestCategoryTableVisible.value = true
            // 	}
            // 	}
            // }
            if (a[i].title == "请求用户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCreatedByTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "负责人") {
              a[i]["on"] = {
                focus(inject) {
                  dialogOwnerVisible.value = true;
                }
              };
            }
            if (a[i].title == "使用人") {
              a[i]["on"] = {
                focus(inject) {
                  dialogUserNameVisible.value = true;
                }
              };
            }

            if (a[i].title == "位置") {
              a[i]["on"] = {
                focus(inject) {
                  dialogLocationTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "部门") {
              a[i]["on"] = {
                focus(inject) {
                  dialogDepartmentVisible.value = true;
                }
              };
            }

            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined) {
              let optionList = [];
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i]["options"].push({ label: element["dname"], value: element["dcode"] });
                });
              });
            }
            formCreateRulesArray.push(a[i] as any);
          }
          formCreateRules.value = formCreateRulesArray;

          tabList.value = [];
          (formCustomRes.formCustomTabsDtos as any).forEach(item => {
            let newItem = JSON.parse(JSON.stringify(item));
            let yydetabAttrsConent = Base64.decode(newItem.tabAttrsConent); //解密
            let aformCreateRules = JSON.parse(yydetabAttrsConent);
            tabList.value.push({
              formCreateRules: aformCreateRules,
              option: {
                submitBtn: false
              },
              formData: {},
              tabName: newItem.tabName,
              tabId: newItem.tabId
            });
          });

          let newParams = JSON.parse(item.templateJson);
          Object.keys(formData.value).forEach(key => {
            formData.value[key] = "";
          });
          let attrVals = newParams.attrVals == undefined ? {} : newParams.attrVals;
          setTimeout(() => {
            formData.value["arrivalDate"] =
              newParams.arrivalDate == undefined ? "" : newParams.arrivalDate.toString().replaceAll("T", " ");
            formData.value.assetsOriginalValue = newParams.assetsOriginalValue == undefined ? "" : newParams.assetsOriginalValue;
            formData.value.buyDate = newParams.buyDate == undefined ? "" : newParams.buyDate.toString().replace("T", " ");
            formData.value.companyName = newParams.companyName == undefined ? "" : newParams.companyName;
            formData.value.companyNo = newParams.companyNo == undefined ? 1 : newParams.companyNo;
            formData.value.ciname = newParams.ciname == undefined ? "" : newParams.ciname;
            formData.value.cino = newParams.cino == undefined ? "" : newParams.cino;
            formData.value.department = newParams.department == undefined ? "" : newParams.department;
            formData.value.departmentName = newParams.department == undefined ? "" : newParams.department;
            formData.value.depreciationIsZeroYears =
              newParams.depreciationIsZeroYears == undefined ? "" : newParams.depreciationIsZeroYears;
            formData.value.lifeCycle = newParams.lifeCycle == undefined ? "" : newParams.lifeCycle;
            formData.value.loc = newParams.locationName == undefined ? "" : newParams.locationName;
            formData.value.locId = newParams.locId == undefined ? "" : newParams.locId;

            traverseTree(LocationSelectList.value[0], node => {
              if (node.attr.id == formData.value.locId) {
                formData.value.loc = node.attr.cname;
              }
            });
            // LocationSelectList.value.forEach(function (LocationElement) {

            // 	if(LocationElement.attr.id==formData.value.locId){

            // 	}

            // });

            formData.value.owner = newParams.owner == undefined ? "" : newParams.owner;
            formData.value.ownerId = newParams.ownerId == undefined ? "" : newParams.ownerId;
            formData.value.statusId = newParams.statusId == undefined ? "" : newParams.statusId;
            formData.value.userName = newParams.userName == undefined ? "" : newParams.userName;
            formData.value.userNameId = newParams.userNameId == undefined ? "" : newParams.userNameId;
            formData.value.warningDate =
              newParams.warningDate == undefined ? "" : newParams.warningDate.toString().replace("T", " ");
            formData.value.warranty = newParams.warranty == undefined ? "" : newParams.warranty;

            Object.keys(attrVals).forEach(key => {
              Object.keys(formData.value).forEach(key2 => {
                if (`${key}` == `${key2}`) {
                  if (`${attrVals[key]}` == "true") {
                    formData.value[`${key2}`] = true;
                  } else {
                    if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                      console.log("数字");
                      //数字
                      formData.value[`${key2}`] = parseInt(`${attrVals[key]}`);
                    } else {
                      //非数字
                      formData.value[`${key2}`] = `${attrVals[key]}`;
                    }
                  }
                }
              });
            });
            tabList.value.forEach(tabitem => {
              Object.keys(attrVals).forEach(key => {
                Object.keys(tabitem.formData).forEach(key2 => {
                  if (`${key}` == `${key2}`) {
                    if (`${attrVals[key]}` == "true") {
                      tabitem.formData[`${key2}`] = true;
                    } else {
                      if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                        console.log("数字");
                        console.log(`${attrVals[key]}`);
                        console.log(parseInt(`${attrVals[key]}`));
                        //数字
                        tabitem.formData[`${key2}`] =
                          `${attrVals[key]}` == null || `${attrVals[key]}` == undefined || `${attrVals[key]}` == ""
                            ? ""
                            : parseInt(`${attrVals[key]}`);
                      } else {
                        //非数字
                        tabitem.formData[`${key2}`] = `${attrVals[key]}`;
                      }
                    }
                  }
                });
              });
            });
          }, 2500);
        } else {
          showCustomerForm.value = false;
          Object.keys(formData.value).forEach(key => {
            formData.value[key] = "";
          });
          // 循环遍历赋值

          for (const key in form) {
            if (Object.prototype.hasOwnProperty.call(form, key) && Object.prototype.hasOwnProperty.call(details.value, key)) {
              if (key == "locId" || key == "categoryNo") {
                form[key] = "" + details.value[key];
              } else if (`${key}`.includes("Date")) {
                form[key] =
                  details.value[key] != undefined && details.value[key] != null
                    ? details.value[key].toString().replace("T", " ")
                    : "";
              } else {
                form[key] = details.value[key] || "";
              }
            }
          }
        }
      });
    }
  });
};
//资产内容模板结束

export interface tabsObj {
  formCreateRules: any[];
  option: {
    submitBtn: false;
  };
  formData: object;
  tabName: string;
  tabId: string;
}
const tabList = ref<tabsObj[]>([]);

//资产分类和资产自定义表单开始
const dialogCicategoryVisible = ref(false);
const categorySelectValue = ref();
const categorySelectList = ref<any>([]);
const showCustomerForm = ref(false);
const formCreateRules = ref<any>([]);
const option = ref({
  submitBtn: false
});
// 父组件的值
const fatherValue = ref({ orgNo: 1 });
const formData = ref({
  arrivalDate: "",
  assetsOriginalValue: "",
  buyDate: "",
  ciname: "",
  cino: "",
  companyName: "",
  companyNo: "",
  department: "",
  departmentName: "",
  depreciationIsZeroYears: "",
  lifeCycle: "",
  loc: "",
  locId: "",
  owner: "",
  ownerId: "",
  statusId: "",
  userName: "",
  userNameId: "",
  warningDate: "",
  warranty: ""
});
const defaultProps = {
  children: "children",
  label: "data"
};
onMounted(() => {
  //请求分类选择树
  getCimClass().then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      if (node.attr.cname == "配置项分类") {
        node["disabled"] = true;
      }
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    let k: any[] = [];
    k.push(res);
    categorySelectList.value = k;
  });
  getCategoryTreeAllData("Location").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    LocationSelectList.value = [res as any];
  });
  getUserDepartment().then(res => {
    let newres = JSON.parse(JSON.stringify(res));
    traverseTree(newres[0], node => {
      node.lable = node.attr.orgNo;
      node.value = node.attr.orgName;
    });
    departmentSelectList.value = newres;
  });
});
const dialogCreatedByTableVisible = ref(false); //创建人
const dialoguserNameTableVisible = ref(false); //创建人
const dialogOwnerVisible = ref(false); //负责人
const dialogUserNameVisible = ref(false); //使用人

//负责人选择子组件弹窗回调方法
const sendOwner = (data: any) => {
  formData.value["ownerId"] = data.userId;
  formData.value["owner"] = data.fullName;
  //失去焦点避免重复打开 对话框
  let inputBox = document.getElementById("customerTypeNameInput") as HTMLInputElement; // 获取输入框元素
  inputBox.focus();
  //(cwangEditor.value as any).editor.focus()
  dialogOwnerVisible.value = false;
};
//使用人选择子组件弹窗回调方法
const sendUserNamer = (data: any) => {
  formData.value["userNameId"] = data.userId;
  formData.value["userName"] = data.fullName;
  //失去焦点避免重复打开 对话框
  let inputBox = document.getElementById("customerTypeNameInput") as HTMLInputElement; // 获取输入框元素
  inputBox.focus();
  //(cwangEditor.value as any).editor.focus()
  dialogUserNameVisible.value = false;
};

const dialogDepartmentVisible = ref(false);
const departmentSelectList = ref<any>([]);

const departmentCustomerSelectValue = ref();
const handleNodeClickDepartment = (data: any) => {
  console.log(data);
  departmentCustomerSelectValue.value = data;
};
const submitDepartment = () => {
  console.log("sdfaadfds");
  if (departmentCustomerSelectValue.value == null || departmentCustomerSelectValue.value == undefined) {
    ElMessage.info("请选择位置");
    return;
  }
  console.log("777777777");
  if ((departmentCustomerSelectValue.value.children as any).length > 0) {
    ElMessage.info("请选择叶子节点");
    return;
  }
  console.log("8888888888");
  console.log(departmentCustomerSelectValue.value);
  formData.value["department"] = departmentCustomerSelectValue.value.attr.orgName;
  formData.value["departmentName"] = departmentCustomerSelectValue.value.attr.orgName;
  //console.log(formData.value)
  //失去焦点避免重复打开 对话框
  let inputBox = document.getElementById("customerTypeNameInput") as HTMLInputElement; // 获取输入框元素
  inputBox.focus();
  // if(cwangEditor.value!=null){
  // 	(cwangEditor.value["editor"] as any).focus()
  // }
  dialogDepartmentVisible.value = false;
};

//客户选择子组件弹窗回调方法
const dialogCiCompanyNoTableVisible = ref(false);
const sendCiCompanyNoData = (data: any) => {
  console.log("dssssssssssssssssssss");
  formData.value["companyName"] = data.orgName;
  formData.value["companyNo"] = data.orgNo;

  //失去焦点避免重复打开 对话框
  let inputBox = document.getElementById("customerTypeNameInput") as HTMLInputElement; // 获取输入框元素
  inputBox.focus();
  dialogCiCompanyNoTableVisible.value = false;
};
const handleNodeClickLocation = (data: any) => {
  console.log(data);
  locationCustomerSelectValue.value = data;
};
// const LocationSelectValue = ref();
const LocationSelectList = ref<any>([]);

const locationCustomerSelectValue = ref();
const dialogLocationTableVisible = ref(false);
const submitLocation = () => {
  console.log("sdfaadfds");
  if (locationCustomerSelectValue.value == null || locationCustomerSelectValue.value == undefined) {
    ElMessage.info("请选择位置");
    return;
  }
  console.log("777777777");
  if ((locationCustomerSelectValue.value.children as any).length > 0) {
    ElMessage.info("请选择叶子节点");
    return;
  }
  console.log("8888888888");
  console.log(locationCustomerSelectValue.value);
  formData.value["loc"] = locationCustomerSelectValue.value.attr.cname;
  formData.value["locId"] = locationCustomerSelectValue.value.attr.id;
  //console.log(formData.value)
  //失去焦点避免重复打开 对话框
  let inputBox = document.getElementById("customerTypeNameInput") as HTMLInputElement; // 获取输入框元素
  inputBox.focus();
  // if(cwangEditor.value!=null){
  // 	(cwangEditor.value["editor"] as any).focus()
  // }
  dialogLocationTableVisible.value = false;
};
interface Tree {
  label: string;
  children?: Tree[];
  attr: any;
}
const handleNodeClickcategory = (data: Tree) => {
  ElMessageBox.confirm("您输入的数据将不会被保存，确定切换表单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      similarFormCustom.value = "";
      dialogCicategoryVisible.value = false;
      serviceDirectoryList.value = [];
      enclosureList.value = [];
      findAllTemplate(data.attr.cno).then(res => {
        //模板
        similarFormCustomOptions.value = res as any;
      });

      findFormCustomByCiCategoryNo(data.attr.cno).then(res => {
        if (res != null) {
          Object.keys(formData.value).forEach(key => {
            formData.value[key] = "";
          });

          showCustomerForm.value = true;
          let newParams = JSON.parse(JSON.stringify(res));
          let yyde = Base64.decode(newParams.formCustomContents); //解密
          console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          for (let i = 0; i < a.length; i++) {
            if (a[i].label != undefined && a[i].label != "") {
              showCustomerForm.value = false;
              break;
            }
            if (a[i].title == "所属客户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCiCompanyNoTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求用户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCreatedByTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "负责人") {
              a[i]["on"] = {
                focus(inject) {
                  dialogOwnerVisible.value = true;
                }
              };
            }
            if (a[i].title == "使用人") {
              a[i]["on"] = {
                focus(inject) {
                  dialogUserNameVisible.value = true;
                }
              };
            }

            if (a[i].title == "位置") {
              a[i]["on"] = {
                focus(inject) {
                  dialogLocationTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "部门") {
              a[i]["on"] = {
                focus(inject) {
                  dialogDepartmentVisible.value = true;
                }
              };
            }

            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined) {
              let optionList = [];
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i]["options"].push({ label: element["dname"], value: element["dcode"] });
                });
              });
            }
            formCreateRulesArray.push(a[i] as any);
          }
          formCreateRules.value = formCreateRulesArray;

          tabList.value = [];
          (newParams.formCustomTabsDtos as any).forEach(item => {
            let newItem = JSON.parse(JSON.stringify(item));
            let yydetabAttrsConent = Base64.decode(newItem.tabAttrsConent); //解密
            let aformCreateRules = JSON.parse(yydetabAttrsConent);
            tabList.value.push({
              formCreateRules: aformCreateRules,
              option: {
                submitBtn: false
              },
              formData: {},
              tabName: newItem.tabName,
              tabId: newItem.tabId
            });
          });
        } else {
          showCustomerForm.value = false;
          // 循环遍历清空表单
          for (const key in form) {
            form[key] = "";
          }
        }
        //赋值分类
        form.categoryNo = data.attr.cno;
        form.categoryName = data.attr.cname;
      });
    })
    .catch(e => {
      console.log(e);
      ElMessage({
        type: "info",
        message: "取消操作"
      });
    });
};
interface TreeNode {
  value: any;
  lable: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}

//资产分类和资产自定义表单结束

interface OrgItem {
  orgNo: string;
  orgName: string;
}

// 所属客户列表
const orgList = computed(() => {
  let list = ref<OrgItem[]>(assetOptions.orgList || []);
  let companyNo = userStore.userInfo.companyNo;
  let hasItem = false;
  list.value.forEach((item: any) => {
    if (item.orgNo === companyNo) {
      hasItem = true;
    }
  });
  if (!hasItem) {
    list.value.push({
      orgName: userStore.userInfo.companyName,
      orgNo: userStore.userInfo.companyNo
    });
  }
  return list.value;
});

interface UniversalItem {
  id: number;
  cno: number;
  label: string;
  cname: string;
  dname: string;
  dcode: string;
}

interface CateItem {
  attr: UniversalItem;
  children: CateItem[];
}

// 配置项分类列表
const cateList = computed(() => {
  let list: any[] = JSON.parse(JSON.stringify(assetOptions.cateList));
  list.forEach((item: any) => {
    item.label = item.attr.cname;
    item.value = item.attr.cno;
    if (item.children.length > 0) {
      item.children.forEach((vo: any) => {
        vo.label = vo.attr.cname;
        vo.value = vo.attr.cno;
      });
    }
  });
  return list;
});

// 状态列表
const statusList = computed<UniversalItem[]>(() => {
  return assetOptions.statusList || [];
});

// 位置列表
const positionList = computed(() => {
  let list: any[] = JSON.parse(JSON.stringify(assetOptions.positionList));
  list.forEach((item: any) => {
    item.label = item.attr.cname;
    item.value = item.attr.id;
    if (item.children.length > 0) {
      item.children.forEach((vo: any) => {
        vo.label = vo.attr.cname;
        vo.value = vo.attr.id;
      });
    }
  });
  return list;
});

const rules = reactive({
  ciname: [{ required: true, message: "请输入资产名称", trigger: "blur" }],
  categoryNo: [{ required: true, message: "请选择配置项分类", trigger: "change" }],
  cino: [{ required: true, message: "请输入固定资产编号", trigger: "blur" }],
  companyNo: [{ required: true, message: "请选择所属客户", trigger: "change" }]
  // owner: [{ required: true, message: "请选择负责人", trigger: "change" }],
  // userName: [{ required: true, message: "请选择使用人", trigger: "change" }]
});

const form = reactive({
  ciId: "",
  ciname: "", // 资产名称
  cino: "", // 资产编号
  categoryNo: "", // 资产分类
  categoryName: "",
  companyNo: "", // 所属客户
  companyName: "",
  statusId: "", // 状态
  locId: "", // 位置id
  loc: "", // 位置中文
  buyDate: "", // 采购日期
  arrivalDate: "", // 到货日期
  warningDate: "", // 预警日期
  lifeCycle: "", // 生命周期
  warranty: "", // 保修期
  assetsOriginalValue: "", // 资产原值
  department: "", // 部门
  owner: "", // 负责人
  ownerId: "",
  userName: "", // 使用人
  userNameId: "",
  depreciationIsZeroYears: "" // 折旧年限
});

// 选择配置项
const selectConfigItemMask = ref();
const selectConfigItem = () => {
  selectConfigItemMask.value?.open();
};
const selectConfigItemChange = e => {
  form.categoryNo = e.cno;
  form.categoryName = e.cname;
};

// 选择部门
const selectDepartmentMask = ref();
// 打开选择部门弹窗
const selectDepartment = () => {
  selectDepartmentMask.value?.open();
};
const departmentChange = (e: any) => {
  form.department = e.orgName;
};

// 查询树中的某项
const findEmployeeById = (arr: any[], value: any) => {
  for (let item of arr) {
    if (item.value) {
      if (item.value === value) {
        return item;
      }
    } else if (item.id) {
      if (item.id === value) {
        return item;
      }
    }
    if (item.children && Array.isArray(item.children)) {
      const result = findEmployeeById(item.children, value);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

const locChange = (e: any) => {
  let data = findEmployeeById(positionList.value, e);
  form.loc = data.label;
};

const companyChange = (e: any) => {
  orgList.value.forEach((item: any) => {
    if (item.orgNo == e) {
      form.companyName = item.orgName;
    }
  });
};

// 选择用户
const selectUserMask = ref();
const selectUserType = ref("");
// 打开选择用户弹窗
const selectUser = (type: string) => {
  selectUserType.value = type;
  selectUserMask.value.open();
};
// 选择了用户
const userChange = (e: { fullName: any }) => {
  // filterForm[selectUserType.value] = e.userId;
  form[selectUserType.value] = e.fullName;
};

const enclosureList = ref<any[]>([]); // 附件列表

// const getEnclosureList = () => {
//   findAllEventAttachment({
//     "eventAttachmentDto.eno": details.value.eno,
//     "eventAttachmentDto.eventType": "itsm.request"
//   }).then((res: any) => {
//     enclosureList.value = res || [];
//   });
// };

import type { UploadProps } from "element-plus";
// 上传附件
const uploadChange: UploadProps["onChange"] = (uploadFile: any) => {
  loading.value = true;
  let params = new FormData();
  params.append("filedata", uploadFile.raw);
  uploadAttr("yuehaishuiwu_zhengshi", params)
    .then(res => {
      console.log(res);
      loading.value = false;
      enclosureList.value.push({
        attachmentName: uploadFile.name,
        url: res.msg,
        size: uploadFile.size
      });
    })
    .catch(() => {
      console.log("err err err");
      loading.value = false;
    });
};

// 删除附件
const delFile = (item: { url: any }) => {
  ElMessageBox.confirm("确定要删除该附件？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      let index = -1;
      enclosureList.value.forEach((vo, idx) => {
        if (vo.url === item.url) {
          index = idx;
        }
      });
      if (index >= 0) {
        let list = [...enclosureList.value];
        list.splice(index, 1);
        enclosureList.value = list;
      }
    })
    .catch(() => {
      // cancel operation
    });
};

// 选择服务
const serviceDirectoryList = ref<any[]>([]);
const selectServesMask = ref();
const showSelectServesMask = () => {
  selectServesMask.value?.open();
};
// 选择服务
const serveChange = (list: any[]) => {
  serviceDirectoryList.value = list;
};

const delServe = (item: { id: any }) => {
  let index = 0;
  serviceDirectoryList.value.forEach((element, idx) => {
    if (element.id == item.id) {
      index = idx;
    }
  });
  serviceDirectoryList.value.splice(index, 1);
};

// 定义 emit 事件
const emit = defineEmits<{
  change: any;
  add: any;
}>();

// 提交保存
const editForm = ref();
const submit = async () => {
  if (showCustomerForm.value == true) {
    //自定义表单
    console.log(formData.value);
    if (formData.value.companyNo == null || formData.value.companyNo == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "请选择所属客户",
        type: "error"
      });

      return;
    }
    if (formData.value.ciname == null || formData.value.ciname == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "请输入资产名称",
        type: "error"
      });
      return;
    }
    if (formData.value.cino == null || formData.value.cino == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "请输入资产编号",
        type: "error"
      });
      return;
    }
    //数据拷贝
    Object.keys(formData.value).forEach(key => {
      form[`${key}`] = `${formData.value[key]}`;
    });

    tabList.value.forEach(tabdata => {
      //选项卡数据拷贝
      Object.keys(tabdata.formData).forEach(key => {
        form[`${key}`] = `${tabdata.formData[key]}`;
      });
    });
  }
  await editForm.value.validate((valid: any, fields: any) => {
    if (valid) {
      // 附件
      let attachmentStr = "";
      if (enclosureList.value.length > 0) {
        enclosureList.value.forEach(item => {
          attachmentStr += item.attachmentName + "==" + item.url + "==" + item.size + "-s-";
        });
      }
      loading.value = true;
      let txt = "";
      if (form.ciId) {
        // 编辑
        txt = serviceDirectoryList.value
          .map(item => {
            return "ciDto.serviceDirectoryNos=" + item.id;
          })
          .join("&");

        cItemUpdate(
          txt,
          {
            "ciDto.isNewForm": true,
            "ciDto.ciId": form.ciId,
            "ciDto.categoryNo": details.value.categoryNo,
            "ciDto.categoryName": details.value.categoryName,
            "ciDto.companyNo": details.value.companyNo,
            "ciDto.ciname": form.ciname,
            "ciDto.cino": form.cino,
            "ciDto.statusId": form.statusId,
            "ciDto.locId": form.locId,
            "ciDto.loc": form.loc,
            "ciDto.buyDate": form.buyDate,
            "ciDto.arrivalDate": form.arrivalDate,
            "ciDto.warningDate": form.warningDate,
            "ciDto.lifeCycle": form.lifeCycle,
            "ciDto.warranty": form.warranty,
            "ciDto.assetsOriginalValue": form.assetsOriginalValue,
            "ciDto.department": form.department,
            "ciDto.owner": form.owner,
            "ciDto.ownerId": form.ownerId,
            "ciDto.userName": form.userName,
            "ciDto.userNameId": form.userNameId,
            "ciDto.depreciationIsZeroYears": form.depreciationIsZeroYears
          },
          form
        )
          .then(() => {
            loading.value = false;
            ElMessage.success("保存成功");
            dialogVisible.value = false;
            emit("change", { message: "保存成功" });
          })
          .catch(() => {
            loading.value = false;
          });
      } else {
        console.log(form);
        // 新增
        txt = "ciDto.isShowBorder=0&ciDto.isNewForm=true";
        if (serviceDirectoryList.value.length > 0) {
          txt =
            "&" +
            serviceDirectoryList.value
              .map(item => {
                return "ciDto.serviceDirectoryNos=" + item.id;
              })
              .join("&");
        }
        cItemSave(
          txt,
          {
            "templateDTO.templateType": "configureItem",
            "templateDTO.templateName": "",
            "templateDTO.templateId": "",
            "ciDTO.formId": 0,
            "ciDto.categoryNo": form.categoryNo,
            "ciDto.categoryName": form.categoryName,
            "ciDto.companyNo": form.companyNo,
            "ciDto.companyName": form.companyName,
            "ciDto.ciname": form.ciname,
            "ciDto.cino": form.cino,
            "ciDto.statusId": form.statusId,
            "ciDto.locId": form.locId,
            "ciDto.loc": form.loc,
            "ciDto.buyDate": form.buyDate,
            "ciDto.arrivalDate": form.arrivalDate,
            "ciDto.warningDate": form.warningDate,
            "ciDto.lifeCycle": form.lifeCycle,
            "ciDto.warranty": form.warranty,
            "ciDto.assetsOriginalValue": form.assetsOriginalValue,
            "ciDto.department": form.department,
            "ciDto.owner": form.owner,
            "ciDto.ownerId": form.ownerId,
            "ciDto.userName": form.userName,
            "ciDto.userNameId": form.userNameId,
            "ciDto.depreciationIsZeroYears": form.depreciationIsZeroYears,
            "ciDto.attachmentStr": attachmentStr // 附件
            // "ciDto.serviceDirectoryNos": serviceDirectoryList.value.map(item => {
            //   return item.id;
            // })
          },
          form
        )
          .then(() => {
            loading.value = false;
            ElMessage.success("保存成功");
            dialogVisible.value = false;
            emit("add", { message: "保存成功" });
          })
          .catch(() => {
            loading.value = false;
          });
      }
    }
  });
};

const details = ref<any>({});
const loading = ref(false);

// 详情
const getData = () => {
  // 获取资产详情
  findById(details.value.ciId)
    .then((res: any) => {
      loading.value = false;
      details.value = {
        ...details.value,
        ...res
      };
      // 循环遍历赋值
      for (const key in form) {
        if (Object.prototype.hasOwnProperty.call(form, key) && Object.prototype.hasOwnProperty.call(details.value, key)) {
          if (key == "locId" || key == "categoryNo") {
            form[key] = "" + details.value[key];
          } else {
            form[key] = details.value[key] || "";
          }
        }
      }
      // 设置关联服务列表
      if (res.serviceDirDtos || res.serviceDirDtos.length > 0) {
        serviceDirectoryList.value = res.serviceDirDtos.map((item: { eventId: any; eventName: any }) => {
          return {
            id: item.eventId,
            cname: item.eventName
          };
        });
      } else {
        serviceDirectoryList.value = [];
      }

      //自定义表单
      findFormCustomByCiCategoryNo(form.categoryNo).then(res => {
        if (res != null) {
          loading.value = true;
          showCustomerForm.value = true;
          //console.log("res")
          //console.log(atob(res.formCustomContents))
          //console.log(decode64(res.formCustomContents))
          let formCustomRes = JSON.parse(JSON.stringify(res));
          let yyde = Base64.decode(formCustomRes.formCustomContents); //解密
          console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          for (let i = 0; i < a.length; i++) {
            if (a[i].label != undefined && a[i].label != "") {
              showCustomerForm.value = false;
              break;
            }
            if (a[i].title == "所属客户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCiCompanyNoTableVisible.value = true;
                }
              };
            }
            // if(a[i].title=="请求分类"){
            // 	a[i]["on"]={
            // 			focus(inject){
            // 				dialogRequestCategoryTableVisible.value = true
            // 	}
            // 	}
            // }
            if (a[i].title == "请求用户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCreatedByTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "负责人") {
              a[i]["on"] = {
                focus(inject) {
                  dialogOwnerVisible.value = true;
                }
              };
            }
            if (a[i].title == "使用人") {
              a[i]["on"] = {
                focus(inject) {
                  dialogUserNameVisible.value = true;
                }
              };
            }

            if (a[i].title == "位置") {
              a[i]["on"] = {
                focus(inject) {
                  dialogLocationTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "部门") {
              a[i]["on"] = {
                focus(inject) {
                  dialogDepartmentVisible.value = true;
                }
              };
            }

            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined) {
              let optionList = [];
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i]["options"].push({ label: element["dname"], value: element["dcode"] });
                });
              });
            }
            formCreateRulesArray.push(a[i] as any);
          }
          formCreateRules.value = formCreateRulesArray;

          tabList.value = [];
          (formCustomRes.formCustomTabsDtos as any).forEach(item => {
            let newItem = JSON.parse(JSON.stringify(item));
            let yydetabAttrsConent = Base64.decode(newItem.tabAttrsConent); //解密
            let aformCreateRules = JSON.parse(yydetabAttrsConent);
            tabList.value.push({
              formCreateRules: aformCreateRules,
              option: {
                submitBtn: false
              },
              formData: {},
              tabName: newItem.tabName,
              tabId: newItem.tabId
            });
          });

          let attrVals = details.value.attrVals == undefined ? {} : details.value.attrVals;

          setTimeout(() => {
            formData.value.arrivalDate =
              details.value.arrivalDate == undefined ? "" : details.value.arrivalDate.toString().replace("T", " ");
            formData.value.assetsOriginalValue =
              details.value.assetsOriginalValue == undefined ? "" : details.value.assetsOriginalValue;
            formData.value.buyDate = details.value.buyDate == undefined ? "" : details.value.buyDate.toString().replace("T", " ");
            formData.value.companyName = details.value.companyName == undefined ? "" : details.value.companyName;
            formData.value.companyNo = details.value.companyNo == undefined ? 1 : details.value.companyNo;
            formData.value.ciname = details.value.ciname == undefined ? "" : details.value.ciname;
            formData.value.cino = details.value.cino == undefined ? "" : details.value.cino;
            formData.value.department = details.value.department == undefined ? "" : details.value.department;
            formData.value.departmentName = details.value.department == undefined ? "" : details.value.department;
            formData.value.depreciationIsZeroYears =
              details.value.depreciationIsZeroYears == undefined ? "" : details.value.depreciationIsZeroYears;
            formData.value.lifeCycle = details.value.lifeCycle == undefined ? "" : details.value.lifeCycle;
            formData.value.loc = details.value.loc == undefined ? "" : details.value.loc;
            formData.value.locId = details.value.locId == undefined ? "" : details.value.locId;
            formData.value.owner = details.value.owner == undefined ? "" : details.value.owner;
            formData.value.ownerId = details.value.ownerId == undefined ? "" : details.value.ownerId;
            formData.value.statusId = details.value.statusId == undefined ? "" : details.value.statusId;
            formData.value.userName = details.value.userName == undefined ? "" : details.value.userName;
            formData.value.userNameId = details.value.userNameId == undefined ? "" : details.value.userNameId;
            formData.value.warningDate =
              details.value.warningDate == undefined ? "" : details.value.warningDate.toString().replace("T", " ");
            formData.value.warranty = details.value.warranty == undefined ? "" : details.value.warranty;

            Object.keys(attrVals).forEach(key => {
              Object.keys(formData.value).forEach(key2 => {
                if (`${key}` == `${key2}`) {
                  if (`${attrVals[key]}` == "true") {
                    formData.value[`${key2}`] = true;
                  } else {
                    if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                      console.log("数字");
                      //数字
                      formData.value[`${key2}`] =
                        `${attrVals[key]}` == null || `${attrVals[key]}` == undefined || `${attrVals[key]}` == ""
                          ? ""
                          : parseInt(`${attrVals[key]}`);
                    } else {
                      //非数字
                      formData.value[`${key2}`] = `${attrVals[key]}`;
                    }
                  }
                }
              });
            });

            tabList.value.forEach(tabitem => {
              Object.keys(attrVals).forEach(key => {
                Object.keys(tabitem.formData).forEach(key2 => {
                  if (`${key}` == `${key2}`) {
                    if (`${attrVals[key]}` == "true") {
                      tabitem.formData[`${key2}`] = true;
                    } else {
                      if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                        console.log("数字");
                        console.log(`${attrVals[key]}`);
                        console.log(parseInt(`${attrVals[key]}`));
                        //数字
                        tabitem.formData[`${key2}`] =
                          `${attrVals[key]}` == null || `${attrVals[key]}` == undefined || `${attrVals[key]}` == ""
                            ? ""
                            : parseInt(`${attrVals[key]}`);
                      } else {
                        //非数字
                        tabitem.formData[`${key2}`] = `${attrVals[key]}`;
                      }
                    }
                  }
                });
              });
            });
            loading.value = false;
          }, 2500);
        } else {
          showCustomerForm.value = false;
          Object.keys(formData.value).forEach(key => {
            formData.value[key] = "";
          });
        }
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

const tabName = ref("one");

const organizationList = ref<any[]>([]);
import type { CascaderProps } from "element-plus";
const departmentProps: CascaderProps = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    if (level == 0) {
      resolve(organizationList.value);
    } else if (level >= 3) {
      findAllOrganization({
        companyNo: userStore.userInfo.companyNo,
        parentOrgNo: node.value,
        _: new Date().getTime()
      }).then((res: any) => {
        res.forEach((item: any) => {
          item.label = item.attr.orgName;
          item.value = "" + item.attr.orgNo;
          item.leaf = item.state ? false : true;
        });
        resolve(res);
      });
    }
  }
};

const open = (item: any) => {
  // 循环遍历清空表单
  for (const key in form) {
    form[key] = "";
  }
  tabName.value = "one";
  enclosureList.value = []; // 清除附件
  dialogVisible.value = true;
  showCustomerForm.value = false;
  if (item) {
    details.value = item;
    loading.value = true;
    getData();
  }

  if (organizationList.value.length == 0) {
    findAllOrganization({
      companyNo: userStore.userInfo.companyNo,
      parentOrgNo: 0,
      _: new Date().getTime()
    }).then((res: any) => {
      res.forEach((item: any) => {
        item.label = item.attr.orgName;
        item.value = "" + item.attr.orgNo;
        if (item.children) {
          item.children.forEach((vo: any) => {
            vo.label = vo.attr.orgName;
            vo.value = "" + vo.attr.orgNo;
            if (vo.children) {
              vo.children.forEach((v: any) => {
                v.label = v.attr.orgName;
                v.value = "" + v.attr.orgNo;
                if (v.children) {
                  v.children.forEach(element => {
                    element.label = element.attr.orgName;
                    element.value = "" + element.attr.orgNo;
                  });
                }
              });
            }
          });
        }
      });
      organizationList.value = res;
    });
  }
};

defineExpose({
  open
});
</script>
<style lang="scss" scoped>
.custom-tree {
  height: 450px; /* 你想要的高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}
.messageIndex {
  z-index: 9999 !important; // 设置的值一定要比2007大，因为dialog的层级是2007
}
</style>
<style lang="scss">
.customMsgCls {
  z-index: 20010 !important;
}
</style>
